<template>
  <div class="min-h-screen flex flex-col bg-gray-100">
    <!-- 工具栏 -->
    <header class="bg-white shadow-md px-6 py-4 flex items-center justify-between">
      <h1 class="text-xl font-semibold text-gray-800">MOZZ电影仓库</h1>
      <div class="flex items-center gap-4">
        <span v-if="directoryPath"
          class="text-sm text-gray-600 bg-gray-50 px-3 py-1 rounded-lg border border-gray-200 max-w-[400px] truncate"
          :title="directoryPath">
          {{ directoryPath }}
        </span>
        <button @click="chooseDirectory"
          class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
          选择目录
        </button>

        <!-- 一键获取按钮 -->
        <button @click="fetchAllMovies" :disabled="movies.length === 0 || downloadingAll"
          class="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-300 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition">
          <template v-if="downloadingAll">
            获取中 {{ downloadProgress.current }}/{{ downloadProgress.total }}
          </template>
          <template v-else>
            一键获取信息
          </template>
        </button>
      </div>
    </header>
    <div class="bg-white px-6 py-2 flex items-center gap-4 shadow-sm">
      <span class="text-sm text-gray-700 font-medium">排列列数：</span>
      <div class="flex gap-2">
        <button v-for="col in [4, 5, 6]" :key="col" @click="setColumns(col)"
          :class="{ 'bg-blue-600 text-white': columnsPerRow === col, 'bg-gray-200 text-gray-700': columnsPerRow !== col }"
          class="px-3 py-1 rounded-lg text-sm font-medium transition">
          {{ col }}
        </button>
      </div>
    </div>
    <!-- 电影列表 -->
    <main class="flex-1 p-6">
      <div v-if="movies.length === 0" class="text-gray-500 text-center mt-10">
        暂无电影，请先选择目录
      </div>
      <ul v-else class="grid gap-6" :style="gridStyle">
        <li v-for="movie in movies" :key="movie.name"
          class="bg-white shadow rounded-lg overflow-hidden hover:shadow-lg transition-transform duration-300 relative"
          @mousedown="startLongPress(movie.name)" @mouseup="cancelLongPress" @mouseleave="cancelLongPress">

          <div class="w-full pb-[150%] bg-gray-200 relative flex items-center justify-center">
            <img v-if="movie.cover" :src="movie.cover"
              class="absolute top-0 left-0 w-full h-full object-cover rounded-t-lg" />
            <span v-else class="absolute text-gray-400 text-4xl mt-[150%]">🎬</span>
          </div>

          <div class="p-3 text-sm text-gray-700 font-medium truncate">
            {{ movie.name }}
          </div>
        </li>
      </ul>
    </main>
  </div>


  <div v-if="showModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
    @click.self="showModal = false">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[80vh] flex flex-col overflow-hidden">
      <!-- 搜索栏固定 -->
      <div class="p-6 border-b border-gray-200 flex flex-col gap-2">
        <h2 class="text-xl font-semibold">电影信息搜索</h2>
        <input v-model="currentMovieName" @change="searchMoviesInfo" type="text"
          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" />
      </div>

      <!-- 内容区域，可滚动 -->
      <div class="p-4 flex-1 overflow-y-auto">
        <!-- loading 状态 -->
        <div v-if="loadingMovie" class="flex justify-center items-center h-full">
          <svg class="animate-spin h-8 w-8 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none"
            viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
          </svg>
        </div>

        <!-- 无搜索结果 -->
        <p v-else-if="searchResults.length === 0" class="text-gray-500 text-center">暂无搜索结果</p>

        <!-- 搜索结果列表 -->
        <div v-else class="p-4 flex-1 overflow-y-auto grid grid-cols-2 md:grid-cols-3 gap-4">
          <div v-for="movie in searchResults" :key="movie.id" @click="fetchMovieDetails(movie)"
            class="flex flex-col items-center cursor-pointer hover:scale-105 transition-transform">
            <!-- 封面 -->
            <img v-if="movie.localPoster" :src="movie.localPoster" class="w-32 h-48 object-cover rounded-md"
              alt="poster" />
            <div class="mt-2 text-center text-sm font-medium text-gray-700 truncate w-32">
              {{ movie.title }}
            </div>
          </div>
        </div>
      </div>
    </div>


    <div v-if="downloading" class="fixed inset-0 z-50 bg-black/50 flex items-center justify-center">
      <div class="bg-white p-6 rounded-lg flex flex-col items-center gap-4">
        <svg class="animate-spin h-8 w-8 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none"
          viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
        </svg>
        <span class="text-gray-700 font-medium">下载中，请稍候...</span>
      </div>
    </div>



    <!-- Toast -->
    <div v-if="showToast"
      class="fixed bottom-6 right-6 bg-black/80 text-white px-4 py-2 rounded-lg shadow-lg z-50 transition-all duration-300">
      {{ toastMessage }}
    </div>
  </div>

</template>
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { searchMoviesList } from '../api/tmdb'
let longPressTimer: number | null = null;

const directoryPath = ref<string>('')
const movies = ref<{ name: string; path: string; cover?: string; details?: any }[]>([])
const toastMessage = ref('');
const showToast = ref(false);

const showDownloadToast = (msg: string) => {
  toastMessage.value = msg;
  showToast.value = true;

  // 自动消失
  setTimeout(() => {
    showToast.value = false;
    toastMessage.value = '';
  }, 3000);
};
/**
 * 选择电影目录
 * @async
 * @returns {Promise<void>}
 */
const chooseDirectory = async (): Promise<void> => {
  const api = (window as any).electronAPI
  if (!api) return

  const path = await api.selectDirectory()
  if (path) {
    directoryPath.value = path
    localStorage.setItem('movieDir', path) // 缓存目录
    movies.value = await api.getMovieList(path)
  }
}

/**
 * 从缓存加载电影列表
 * @async
 * @returns {Promise<void>}
 */
const loadMoviesFromCache = async (): Promise<void> => {
  const api = (window as any).electronAPI
  if (!api) return

  const cachedPath = localStorage.getItem('movieDir')
  if (cachedPath) {
    directoryPath.value = cachedPath
    movies.value = await api.getMovieList(cachedPath)
  }
}

const showModal = ref(false);
const currentMovieName = ref('');
let selectedMovieName = '';
/**
 * 开始长按事件
 * @param {string} name - 电影名称
 */
const startLongPress = (name: string): void => {
  longPressTimer = window.setTimeout(() => {
    currentMovieName.value = name;
    selectedMovieName = name;
    showModal.value = true;
    searchMoviesInfo()
  }, 600); // 长按 600ms
}

/**
 * 取消长按事件
 */
const cancelLongPress = (): void => {
  if (longPressTimer) {
    clearTimeout(longPressTimer);
    longPressTimer = null;
  }
}

/**
 * 搜索电影信息
 */
const searchResults = ref<any[]>([])
const loadingMovie = ref(false)
const searchMoviesInfo = async (): Promise<void> => {
  loadingMovie.value = true
  try {
    const movies = await (window as any).electronAPI.searchMovies(currentMovieName.value)
    if (movies.error) {
      console.error('搜索电影失败:', movies.message)
      return
    }

    // 遍历电影，下载封面
    for (const movie of movies) {
      if (movie.poster_path) {
        try {
          const localPath = await (window as any).electronAPI.downloadImageBase64(
            `https://image.tmdb.org/t/p/w200${movie.poster_path}`
          )
          movie.localPoster = localPath
        } catch (err) {
          console.error('下载封面失败:', err)
          movie.localPoster = '' // 下载失败，留空
        }
      } else {
        movie.localPoster = '' // 无封面
      }
    }

    searchResults.value = movies
  } finally {
    loadingMovie.value = false
  }
}


/** 电影详情 */
const downloading = ref(false);
const fetchMovieDetails = async (movie: any): Promise<void> => {
  if (!directoryPath.value) return;
  downloading.value = true;  // 显示 mask
  showModal.value = false;   // 关闭搜索弹窗

  // 电影文件夹路径（使用原始电影名）
  const movieDir = `${directoryPath.value}/${selectedMovieName}`;

  // 调用主进程保存 JSON 和下载封面
  const result = await (window as any).electronAPI.saveMovieDetails(movie.id, movieDir);
  if (!result.success) {
    console.error('保存电影失败:', result.error);
    showDownloadToast('保存电影失败');
    return;
  } else {
    showDownloadToast('保存电影成功');
  }

  // 重新加载电影列表，封面显示本地图片
  movies.value = await (window as any).electronAPI.getMovieList(directoryPath.value);

  downloading.value = false; // 关闭 mask
}



const downloadingAll = ref(false);
const downloadProgress = ref({ current: 0, total: 0 });
const fetchAllMovies = async () => {
  if (!directoryPath.value || movies.value.length === 0) return;

  downloadingAll.value = true;
  downloadProgress.value = { current: 0, total: movies.value.length };

  for (let i = 0; i < movies.value.length; i++) {
    const movie = movies.value[i];
    if (movie.details) {
      downloadProgress.value.current = i + 1;
      continue;
    }
    try {
      let movieId = ''
      // 如果没有 TMDB ID，则搜索第一个结果作为默认
      const searchResults = await (window as any).electronAPI.searchMovies(movie.name);
      console.log('searchResults', searchResults)
      if (Array.isArray(searchResults) && searchResults.length > 0) {
        movieId = searchResults[0].id;
      }

      // 获取 TMDB 详情
      if (movieId) {
        const movieDir = `${directoryPath.value}/${movie.name}`;
        await (window as any).electronAPI.saveMovieDetails(movieId, movieDir);
      }

    } catch (err) {
      console.error('获取电影信息失败:', movie.name, err);
    }

    // 更新进度
    downloadProgress.value.current = i + 1;
  }

  // 重新加载电影列表，封面为本地 Base64
  movies.value = await (window as any).electronAPI.getMovieList(directoryPath.value);

  downloadingAll.value = false;
  showDownloadToast('所有电影信息获取完成！');
};


// 每行显示多少列
const columnsPerRow = ref<number>(4);
const setColumns = (num: number) => {
  columnsPerRow.value = num;
  localStorage.setItem('columnsPerRow', num.toString());
};
const gridStyle = computed(() => ({
  display: 'grid',
  gridTemplateColumns: `repeat(${columnsPerRow.value}, minmax(0, 1fr))`,
  gap: '1.5rem',          // Tailwind gap-6 = 1.5rem
  transition: 'grid-template-columns 0.5s ease'
}));
// 页面加载时自动读取缓存
onMounted(() => {
  loadMoviesFromCache()
  const savedCols = localStorage.getItem('columnsPerRow');
  if (savedCols) columnsPerRow.value = parseInt(savedCols);
})
</script>

<style lang="css">
.movie-enter-active,
.movie-leave-active {
  transition: all 0.3s ease;
}

.movie-enter-from,
.movie-leave-to {
  opacity: 0;
  transform: scale(0.95);
}

.movie-enter-to,
.movie-leave-from {
  opacity: 1;
  transform: scale(1);
}
</style>